package com.zlmediakit.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.zlmediakit.R;
import com.zlmediakit.bean.Rtp;
import com.zlmediakit.jni.ZLMediaKit;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * @author Administrator
 */
@SuppressLint("HandlerLeak")
class MediaServerActivity extends Activity implements Camera.PreviewCallback {
    public static final String TAG = "ZLMediaKit";
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.INTERNET"};

    Context context;
    private ZLMediaKit.MediaPlayer _player;
    private ZLMediaKit.MediaPlayerCallBack mediaPlayerCallBack;
    private ZLMediaKit.MediaFrame _mediaFrame;
    String local_ip = "10.0.0.53";
    String ip = "127.0.0.1";
    int port;
    String secret = "035c73f7-bb6b-4889-a715-d9eb2d1925cc";
    String stream_id = "1234";
    String vhost = "__defaultVhost__";
    String ssrc = "";

    final int OPEN_RTP_SERVER = 10000;
    private Camera camera;
    private boolean ispreview = false;
    SurfaceHolder surfaceHolder;
    SurfaceView surface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_server);
        context = this;
        initZLMediaKit();
        surface = findViewById(R.id.surfaceview);
        surfaceHolder = surface.getHolder();
        surfaceHolder.setFormat(SurfaceHolder.SURFACE_TYPE_HARDWARE);
    }


    void initZLMediaKit() {
        boolean permissionSuccess = true;
        for (String str : PERMISSIONS_STORAGE) {
            int permission = ActivityCompat.checkSelfPermission(this, str);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 1);
                permissionSuccess = false;
                break;
            }
        }

        String sd_dir = Environment.getExternalStoragePublicDirectory("").toString();
        if (permissionSuccess) {
            Toast.makeText(this, "你可以修改配置文件再启动：" + sd_dir + "/zlmediakit.ini", Toast.LENGTH_LONG).show();
            Toast.makeText(this, "SSL证书请放置在：" + sd_dir + "/zlmediakit.pem", Toast.LENGTH_LONG).show();
//            start_play();
        } else {
            Toast.makeText(this, "请给予我权限，否则无法启动测试！", Toast.LENGTH_LONG).show();
        }
        ZLMediaKit.startDemo(sd_dir);
    }

    public void open_preview(View view) {
        if (!ispreview) {
            camera = Camera.open();
            ispreview = true;
        }
        try {
            camera.setPreviewDisplay(surfaceHolder);
            Camera.Parameters parameters = camera.getParameters();
            parameters.setPictureFormat(PixelFormat.JPEG);
            parameters.set("jpeg-quality", 100);
            camera.setParameters(parameters);
            camera.startPreview();
            camera.setDisplayOrientation(0);
            camera.autoFocus(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void open_rtp(final View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 1.创建Client
                OkHttpClient client = new OkHttpClient.Builder().build();
                // 2.创建Request
                String url = "http://127.0.0.1:8080/index/api/openRtpServer";
//                Request request = new Request.Builder().post(formBodyBuilder.build()).url(url).build();
                String stringBuilder = url + "?secret=" + secret +
                        "&port=0" +
                        "&enable_tcp=0" +
                        "&stream_id=" + stream_id;
                final Request request = new Request.Builder().get().url(stringBuilder).build();
                Log.d(TAG, "请求：" + request.toString());
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        final String result = response.body().string();
                        Log.d(TAG, "openRtpServer返回值：" + result);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Rtp rtp = JSONObject.parseObject(result, Rtp.class);
                                port = rtp.getPort();
                            }
                        });

                    }
                });
            }
        }).start();
    }


    public void add_push_proxy(final View view) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                // 1.创建Client
//                OkHttpClient client = new OkHttpClient.Builder().build();
//                // 2.创建Request
//                String url = "http://127.0.0.1:8080/index/api/addStreamPusherProxy";
//                String stringBuilder = url +
//                        "?secret=" + secret +
//                        "&vhost=" + vhost +
//                        "&schema=rtmp" +
//                        "&app=live" +
//                        "&stream=" + stream_id +
//                        "&dst_url=rtmp://" + ip + "/live/" + stream_id;
//                final Request request = new Request.Builder().get().url(stringBuilder).build();
//                Log.d(TAG, "请求：" + request.toString());
//                Call call = client.newCall(request);
//                call.enqueue(new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                    }
//
//                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
//                    @Override
//                    public void onResponse(Call call, final Response response) throws IOException {
//                        final String result = response.body().string();
//                        Log.d(TAG, "addStreamPusherProxy返回值：" + result);
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Rtp rtp = JSONObject.parseObject(result, Rtp.class);
//                                port = rtp.getPort();
//                            }
//                        });
//
//                    }
//                });
//            }
//        }).start();

        Intent intent = new Intent();
        intent.setClass(context, PushActivity.class);
        startActivity(intent);
    }

    /***
     * 添加拉流代理
     */
    public void add_pull_proxy(final View view) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                // 1.创建Client
//                OkHttpClient client = new OkHttpClient.Builder().build();
//                // 2.创建Request
//                String url = "http://127.0.0.1:8080/index/api/addStreamProxy";
//                String stringBuilder = url +
//                        "?secret=" + secret +
//                        "&vhost=" + vhost +
//                        "&app=live" +
//                        "&stream=" + stream_id +
//                        "&url=rtmp://" + ip +
//                        "/live/" + "test" +
//                        "&enable_hls=1" +
//                        "&enable_mp4=1" +
//                        "&rtp_type=0";
//                final Request request = new Request.Builder().get().url(stringBuilder).build();
//                Log.d(TAG, "请求：" + request.toString());
//                Call call = client.newCall(request);
//                call.enqueue(new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                    }
//
//                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
//                    @Override
//                    public void onResponse(Call call, final Response response) throws IOException {
//                        final String result = response.body().string();
//                        Log.d(TAG, "addStreamProxy返回值：" + result);
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Rtp rtp = JSONObject.parseObject(result, Rtp.class);
//                                port = rtp.getPort();
//                            }
//                        });
//
//                    }
//                });
//            }
//        }).start();


        Intent intent = new Intent();
        intent.setClass(context, PullActivity.class);
        startActivity(intent);
    }


    //开始录制
    public void start_record(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 1.创建Client
                OkHttpClient client = new OkHttpClient.Builder().build();
                // 2.创建Request
                String url = "http://127.0.0.1:8080/index/api/startRecord";
                // 3.构建表单参数
                String stringBuilder = url + "?secret=" + secret + "&type=1" +
                        "&vhost=" + vhost +
                        "&app=live" +
                        "&stream=" + stream_id;
                Request request = new Request.Builder().get().url(stringBuilder).build();
                Log.d(TAG, "请求参数" + stringBuilder);

                // 3.call execute同步
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 异步，回调在子线程中执行
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "失败返回值：" + call.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "startSendRtp返回值：" + response.body().string());
                    }
                });
            }
        }).start();

    }

    /***  请求参数
     //    secret	Y	api操作密钥(配置文件配置)，如果操作ip是127.0.0.1，则不需要此参数
     //    vhost	Y	虚拟主机，例如__defaultVhost__
     //    app	Y	应用名，例如 live
     //    stream	Y	流id，例如 test
     //    ssrc	Y	推流的rtp的ssrc,指定不同的ssrc可以同时推流到多个服务器
     //    dst_url	Y	目标ip或域名
     //    dst_port	Y	目标端口
     //    is_udp	Y	是否为udp模式,否则为tcp模式
     //    src_port	N	使用的本机端口，为0或不传时默认为随机端口
     */
    public void send_rtp(View view) throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 1.创建Client
                OkHttpClient client = new OkHttpClient.Builder().build();
                // 2.创建Request
                String url = "http://127.0.0.1:8080/index/api/startSendRtp";
                // 3.构建表单参数
                String stringBuilder = url + "?secret=" + secret +
                        "&vhost=" + vhost +
                        "&app=live" +
                        "&stream=" + stream_id +
                        "&ssrc=1000" +
                        "&dst_url=" + local_ip +
                        "&dst_port=" + port +
                        "&is_udp=1" +
                        "&src_port=0";
                Request request = new Request.Builder().get().url(stringBuilder).build();
                Log.d(TAG, "请求参数" + stringBuilder);

                // 3.call execute同步
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 异步，回调在子线程中执行
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "失败返回值：" + call.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "startSendRtp返回值：" + response.body().string());
                    }
                });
            }
        }).start();
    }

    public void get_config(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 1.创建Client
                OkHttpClient client = new OkHttpClient.Builder().build();
                // 2.创建Request
                String url = "http://127.0.0.1:8080/index/api/getServerConfig" + "?secret=" + secret;
                Request request = new Request.Builder().get().url(url).build();
                Log.d(TAG, "请求：" + request.toString());

                // 3.call execute同步
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 异步，回调在子线程中执行
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "失败返回值：" + call.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "返回值：" + response.body().string());
                    }
                });
            }
        }).start();

    }


    private void start_play() {
        _player = new ZLMediaKit.MediaPlayer("rtmp://127.0.0.1/live/1234?vhost=__defaultVhost__", new ZLMediaKit.MediaPlayerCallBack() {
            @Override
            public void onPlayResult(int code, String msg) {
                Log.d(TAG, "onPlayResult:" + code + "," + msg);
            }

            @Override
            public void onShutdown(int code, String msg) {
                Log.d(TAG, "onShutdown:" + code + "," + msg);
            }

            @Override
            public void onData(ZLMediaKit.MediaFrame frame) {
                Log.d(TAG, "onData:"
                        + "是否为视频" + frame.trackType + ","
                        + "编码类型" + frame.codecId + ","
                        + "解码时间戳" + frame.dts + ","
                        + "显示时间戳" + frame.pts + ","
                        + "是否为关键帧" + frame.keyFrame + ","
                        + "前缀长度" + frame.prefixSize + ","
                        + "数据长度" + frame.data.length);


            }
        });
    }


    @Override
    public void onPreviewFrame(byte[] bytes, Camera camera) {
        Log.d(TAG, bytes.toString());
    }


}
